<template>
  <div>
    <form class="card comment-form" @submit.prevent="addComment">
      <div class="card-block">
        <textarea
          v-model="commentBody"
          class="form-control"
          placeholder="Write a comment..."
          rows="3"
        ></textarea>
      </div>
      <div class="card-footer">
        <img :src="user && user.image" class="comment-author-img" />
        <button class="btn btn-sm btn-primary" :disabled="!commentBody">Post Comment</button>
      </div>
    </form>

    <div class="card" v-for="(comment, index) in comments" :key="index">
      <div class="card-block">
        <p class="card-text">{{ comment.body }}</p>
      </div>
      <div class="card-footer">
        <nuxt-link
          :to="{
            name: 'profile',
            params: {
              username: comment.author.username,
            },
          }"
          class="comment-author"
        >
          <img :src="comment.author.image" class="comment-author-img" />
        </nuxt-link>&nbsp;
        <nuxt-link
          :to="{
            name: 'profile',
            params: {
              username: 'lanpang9661',
            },
          }"
          class="comment-author"
        >{{ comment.author.username }}</nuxt-link>
        <span class="date-posted">
          {{
          comment.createAt | date("MMM DD, YYYY")
          }}
        </span>
        <span
          class="mod-options"
          v-if="comment.author.username === user.username"
          @click="delComment(comment.id)"
        >
          <i class="ion-trash-a"></i>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getArticleComments, addComment, delComment } from "@/api/article";

export default {
  name: "ArticleComment",
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      comments: [], // 评论列表
      commentBody: ""
    };
  },
  computed: {
    ...mapState(["user"])
  },
  mounted() {
    this.updateComments();
  },
  methods: {
    async addComment() {
      await addComment(this.article.slug, this.commentBody);
      this.updateComments();
    },
    async updateComments() {
      const { data } = await getArticleComments(this.article.slug);
      this.comments = data.comments;
    },
    async delComment(id) {
      await delComment(this.article.slug, id);
      this.updateComments();
    }
  }
};
</script>